<template>
  <div class="ordermap-containter">
    <div class="ordermap-fifter">
      <el-form :inline="true" :model="ordermapform" class="demo-form-inline">
        <el-form-item label="配送时间">
          <el-date-picker size="small" v-model="Launchdate" type="daterange" range-separator="至" start-placeholder="开始日期"
            :clearable='false' end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item width="300px">
          <el-checkbox v-model="shownumchecked" border="" size="small" @change='handleshownumchecked'>
            <span>显示数量</span>
          </el-checkbox>
        </el-form-item>
        <el-form-item width="300px">
          <el-checkbox v-model="warehousescope" border="" size="small" @change='handlewarehousescope'>
            <span>显示仓库范围</span>
          </el-checkbox>
        </el-form-item>


        <el-form-item>
          <el-button type="primary" plain size="small" icon="el-icon-search" @click="handleFilter(Launchdate)">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="ordermap" :style="{'height':curHeight+'px'}">
      <el-amap vid="container" :zoom="zoom" :center="center" ref="map" :style="{'height':curHeight+'px'}" :events='events'>
        <el-amap-marker v-if="markers&&markers.length>0" v-for="(marker,index) in markers" :key="index" :position="marker.position"></el-amap-marker>
      </el-amap>
      <!-- <div id="container" :style="{'width:100%;height':curHeight+'px'}" v-if="shownumchecked==false"></div> -->
    </div>
  </div>
</template>
<script>
  import {
    deptdepts,
    // getExcelShowData
    getWarehousesByDeptIds,
    getHeatMap
  } from "@/api/statistics"
  var markers = [],
    heatmap = null,gridLayer = null;
  export default {
    data() {
      return {
        cityList: [],
        ordermapform: {
          bottomRight: null, //地图右下角
          topLeft: null, //地图左上角
          deptIds: [], //
          startDeliveryTime: this.dayjs(
              new Date()
            )
            .format("YYYY-MM-DD 00:00:00")
            .toString(), //配送时间「开始」
          endDeliveryTime: this.dayjs(
              new Date()
            )
            .format("YYYY-MM-DD 23:59:59")
            .toString(), //配送时间「结束」
          size: 2999,
          precision:'',

          // city: 1,
          // timeType: 2,

        },
        Launchdate: [
          this.dayjs(
            new Date()
          )
          .format("YYYY-MM-DD 00:00:00")
          .toString(),
          this.dayjs(
            new Date()
          )
          .format("YYYY-MM-DD 23:59:59")
          .toString(),
        ],
        curHeight: 0,
        cityName: '',
        // 地图数据--------------------------------------------------------------------------------
        zoom: 4,
        center: [116.30946, 39.937629],
        markers: [],
        getAreaScope: '', // 覆盖物区域
        mapCenter: [121.59996, 31.197646],
        latitudeFlag: false, // 是否改变了城市
        overlayGroups: [],
        addressList: [],
        addressFlag: false, // 地址详情列表的显隐
        isaddressFlag: false, // 地址详情列表的显隐
        currentIndex: '', // 地图列表激活
        shownumchecked: false,
        warehousescope: false,
        heatmapData: [],
        maplist: [],
        heatmap: [],
        events: {
          'moveend': () => {
            this.logMapBounds(this.$refs.map.$amap)
            this.handleshownumchecked(this.shownumchecked)
          },
          // 'zoomend': () => {
          //   this.logMapBounds(this.$refs.map.$amap)
          //   this.handleshownumchecked(this.shownumchecked)
          // },
          'click': (e) => {
            // alert('map clicked');
          }
        },


      }
    },
    created() {
      this.beforeMount(180);
    },
    mounted() {
      this.beforeMount(180);


      setTimeout(() => {
        this.handlewarehousescope(this.warehousescope);
        this.handleshownumchecked(this.shownumchecked)
      }, 0.4 * 1000);


    },
    methods: {
      handlewarehousescope(val) {
        if (this.shownumchecked == true) {
          if (this.$refs.map.$amap) {
            this.$refs.map.$amap.clearMap();
          }
          if(heatmap!=null){
            heatmap.setDataSet({
              data: [],
            })
          }
          this.getArea(this.warehousescope);
          this.ordershowMapnum(this.$refs.map.$amap)

        } else {
          if (this.$refs.map.$amap) {
             this.$refs.map.$amap.view.map.Ce.overlays = [];
            this.$refs.map.$amap.clearMap();
          }
          this.getArea(this.warehousescope);
          this.ordershowMapHead(this.$refs.map.$amap);
        }
      },
      //获取屏幕
      beforeMount(height) {
        var h =
          document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - height; //减去页面上固定高度height
      },
      // citydataList() {
      //   deptdepts("").then(response => {
      //     this.cityList = response.data.data;
      //     this.ordermapform.city = response.data.data[0].id;
      //     this.cityName = response.data.data[0].deptName;

      //     var mapObj = new AMap.Map("container", {
      //       resizeEnable: true,
      //       center: [116.30946, 39.937629],
      //       zoom: 3 //地图显示的缩放级别
      //     });
      //     this.logMapBounds(mapObj);
      //     this.getArea();
      //     //绑定地图移动与缩放事件

      //   });
      // },
      // handleCityId(data) {
      //   this.ordermapform.city = data.value;
      //   this.cityName = data.label;
      // },
      // getdeptIdsIds(data) {
      //   this.deptIdsIdslist = data;
      // },
      // 查询
      handleFilter(times) {
        setTimeout(() => {
          this.logMapBounds(this.$refs.map.$amap)
        }, 0.1 * 1000);
        if (times) {
          this.ordermapform.startDeliveryTime = this.dayjs(
              times[0]
            )
            .format("YYYY-MM-DD 00:00:00")
            .toString();
          this.ordermapform.endDeliveryTime = this.dayjs(
              times[1]
            )
            .format("YYYY-MM-DD 23:59:59")
            .toString();
        }
        this.handleshownumchecked(this.shownumchecked)
        this.handlewarehousescope(this.warehousescope);
      },

      //根据城市获取地图位置
      getMapaddress(name) {
        var MSearch;
        var mapObj = new AMap.Map("container", {
          resizeEnable: true,
          center: [116.30946, 39.937629],
          zoom: 3 //地图显示的缩放级别
        });
        mapObj.plugin(
          ["AMap.PlaceSearch"],
          () => {
            // mapObj.addControl(new AMap.ToolBar())
            // mapObj.addControl(new AMap.Scale())
            MSearch = new AMap.PlaceSearch({
              //构造地点查询类
              city: '北京市' //城市
            });
            AMap.event.addListener(MSearch, "complete", this.keywordSearch_CallBack) //返回地点查询结果
            MSearch.search(name); //关键字查询
          }
        );
      },
      keywordSearch_CallBack(data) {
        var mapObj = new AMap.Map("container", {
          resizeEnable: true
        });
        var poiArr = data.poiList.pois
        var resultCount = poiArr.length
        this.poiArr = poiArr; //左边要渲染的数据
        mapObj.setFitView()
        mapObj.setZoomAndCenter(14, [poiArr[0].location.lng, poiArr[0].location.lat]);
        this.newcenter = [poiArr[0].location.lng, poiArr[0].location.lat];

      },
      //参库范围
      getArea(valshow) {
        if (valshow == true) {
          if(this.overlayGroups.length > 0){
            //从内存加载
            this.getAreaScopeMethod(
              this.overlayGroups,
              this.marker,
              this.$refs.map.$amap
            );
            return;
          }
          //查询数据
          getWarehousesByDeptIds({
            deptId: 1
          }).then(res => {
            this.getAreaScope = res.data.data;
            var isPointInRingList = [];
            var marker = [];
            var overlayGroupsArray = [];
            var markerslongitude = [],
              markerslatitude;
            this.markers = [];

            let result = res.data.data;
            result.forEach((item, resultindex) => {
              marker.push([item.longitude, item.latitude, `${item.name}`])
              if (result[resultindex].geoJson.geometry !== '') {
                overlayGroupsArray.push(result[resultindex].geoJson.geometry.coordinates[0])
                result[resultindex].geoJson.geometry.coordinates[0].forEach((item) => {
                  isPointInRingList.push(item)
                })
              }
            })
            if (this.latitude !== '' && this.latitude !== '' && this.addressCopyname !== '' && this.latitudeFlag) {
              marker.push([this.longitude, this.latitude, this.addressCopyname]);
            }
            this.markers = marker;
            this.getAreaScopeArray = isPointInRingList;
            this.overlayGroups = overlayGroupsArray;
            this.getAreaScopeMethod(
              this.overlayGroups,
              marker,
              this.$refs.map.$amap
            );
          })
        } else {
          if (this.$refs.map.$amap) {
            this.$refs.map.$amap.view.map.Ce.overlays = [];
            this.$refs.map.$amap.clearMap();
          }
        }

      },
      // 划区域模块
      getAreaScopeMethod(subCoordinate, markeritem, map) {
        var
          path = subCoordinate;
        var polygon = new AMap.Polygon({
          path: path,
          strokeColor: "#000",
          strokeWeight: 3,
          strokeOpacity: 1,
          fillOpacity: 0.4,
          fillColor: 'transparent',
          zIndex: 2,
        });
        // 缩放地图到合适的视野级别
        map.add(polygon);
        this.markers.forEach((item, index) => {
          if (this.latitudeFlag) {
            var marker = new AMap.Marker({
              position: new AMap.LngLat(item[0], item[1]),
              // size: new AMap.Size(15, 20),
              icon: new AMap.Icon({
                image: `${index == (this.markers.length - 1)? '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png': '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png'}`,
                size: new AMap.Size(20, 30), //图标所处区域大小
                imageSize: new AMap.Size(20, 30) //图标大小
              }),

            })
          } else {
            var marker = new AMap.Marker({
              position: new AMap.LngLat(item[0], item[1]),
              // size: new AMap.Size(15, 20),
              icon: new AMap.Icon({
                image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                size: new AMap.Size(20, 30), //图标所处区域大小
                imageSize: new AMap.Size(20, 30) //图标大小
              }),
            })
          }
          marker.setLabel({
            offset: new AMap.Pixel(10, 10), //设置文本标注偏移量
            content: `<div class='info' >${item[2]}</div>`, //设置文本标注内容
            direction: 'top' //设置文本标注方位
          });
          // map.add(marker)
          map.add([marker, polygon]);
        })
        // 缩放地图到合适的视野级别
        // map.setFitView([polygon]);
        // this.logMapBounds(map);
      },
      logMapBounds(map) {
        var bounds = map.getBounds();
        this.ordermapform.bottomRight = {
          lat: bounds.southwest.lat,
          lng: bounds.southwest.lng,
        }
        this.ordermapform.topLeft = {
          lat: bounds.northeast.lat,
          lng: bounds.northeast.lng,
        }
      },

      //热力图
      isSupportCanvas() { //判断浏览区是否支持canvas
        var elem = document.createElement('canvas');
        return !!(elem.getContext && elem.getContext('2d'));
      },
      //热力图是否显示数量
      handleshownumchecked(val) {
        if (val) {
          this.clearHeatmap();//清除热力图层
          this.getArea(this.warehousescope);//加载配送范围
          this.ordershowMapnum(this.$refs.map.$amap)//加载文本图

        } else {
          this.clearGridLayer();//清除文字图层
          this.getArea(this.warehousescope);//加载配送范围
          this.ordershowMapHead(this.$refs.map.$amap);//加载热力图
        }


      },
      /**渲染地图订单数量文本*/
      ordershowMapnum(map) {
        let vm = this;
        this.ordermapform.precision=map.getZoom()
        getHeatMap(this.ordermapform).then(res => {
         if (res.data.data&&res.data.data.length>0) {
           var lst = eval(res.data.data);
           //初始化图层
           vm.initGridLayer(map);
           //渲染图层
           vm.drawGridLayer(lst);
          }
        })


      },
      /**初始化文字图层*/
      initGridLayer(map){
        if(gridLayer == null) {
          gridLayer = new Loca.GridLayer({
            map: map,
            fitView: false,
            collision: false,  // 是否开启文字自动避让
            zIndex: 201
          });
          gridLayer.setOptions({
            unit: 'px',
            style: {
              //color: ['#253494', '#225ea8', '#1d91c0', '#41b6c4', '#7fcdbb', '#c7e9b4', '#edf8b1'],
              radius: 17,
              borderWidth: 1,
              borderColor: '#876583',
              opacity: 0.75,
              gap: 2,
              height: [0, 0],
              text: {
                content: function(v){
                  return v.value.sum;
                },
                direction: 'center',  // 文字方位
                fontSize: 10,  // 文字大小
                fillColor: '#03101F',
                strokeColor: 'rgba(37,182,220,0)',  // 文字描边颜色
                strokeWidth: 0,  // 文字描边宽度
              }
            }

          });

        }
      },
      /**渲染文字图层*/
      drawGridLayer(data){
        gridLayer.setData(data, {
          lnglat: function (obj) {
            return [obj.value.lng, obj.value.lat]
          },
          value: 'count',
          type: 'json'
        });
        gridLayer.show();
        gridLayer.render();
      },
      /**清除文字图层*/
      clearGridLayer(){
        if(gridLayer != null){
          gridLayer.hide();
        }
      },
      /**清除热力图*/
      clearHeatmap(){
        if (heatmap != null) {
          heatmap.setDataSet({
            data: [],
          })
        }
      },
      ordershowMapHead(map) {
        this.ordermapform.precision=map.getZoom()
        getHeatMap(this.ordermapform).then(res => {
          if (res.data.data&&res.data.data.length>0) {
            console.log(heatmap, 'heatmap,22')
            if (heatmap == null) {
              map.plugin(["AMap.Heatmap"], function() {
                //初始化heatmap对象
                heatmap = new AMap.Heatmap(map, {
                  radius: 20, //给定半径
                  opacity: [0, 0.6],
                });
                //设置数据集
                heatmap.setDataSet({
                  data: res.data.data,
                  // max: 10
                });
              });
            } else { //设置数据集
              heatmap.setDataSet({
                data: res.data.data,
                // max: 10
              });

            }

          }

        })

      }

    }
  }
</script>

<style lang="scss" scoped>
  .ordermap-containter {
    padding: 10px;

    .ordermap-fifter {
      .el-form-item {
        margin-bottom: 10px;
      }
    }
    // .info{
    //   background: rgba(0, 87, 255, 0.9);
    //       height: 25px;
    //       width: 25px;
    //       border-radius: 12.5px;
    //       line-height: 25px;
    //       color: rgb(255, 255, 255);
    //       font-size: 14px;
    //       text-align: center;
    // }

  }
</style>
